package com.msmall.community.tag;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.cache.CacheFactory;
import com.msmall.base.util.ConstantDB;
import com.msmall.base.util.Constants;
import com.msmall.community.common.CascadeCollection;
import com.msmall.community.dpt.model.Department;
import com.msmall.community.dpt.model.Segment;

public class DepartmentTag  extends TagSupport {

	private static final long serialVersionUID = 6445632228446931692L;

	private static final Log logger = LogFactory.getLog(DepartmentTag.class);
	
	private String type;// dpt seg
	
	private String action;// name select
	
	private String property;
	
	public int doStartTag() throws JspException {
		return (SKIP_BODY);
	}

	public int doEndTag() throws JspException {
		JspWriter writer = pageContext.getOut();
		
		String message = "";
		try {
			if("dpt".equalsIgnoreCase(type)){
				if("name".equalsIgnoreCase(action)){ //通过栏目ID查找栏目中文名称
					Department department = getDepartment(Long.valueOf(property));
					if(department == null){
						message = "顶级分类";
					}else{
						message = department.getTitle();
					}
				}
				if("select".equalsIgnoreCase(action)){ //显示所有的栏目
					StringBuffer buffer = new StringBuffer();
					Iterator<CascadeCollection<Department>> its = getAllDepartments();
					
					Department current = null;
					Long parentid = null;
					if(null != property && !"".equals(property.trim())){
						current = getDepartment(Long.valueOf(property));
						parentid = current.getParentid();
					}
					
					buffer.append("<option value=\"" + ConstantDB.CASCADE_ID_TOP+"\">顶级分类</option>");
					if(its != null){
						while(its.hasNext()){
							Department dpt = its.next().getCurrent();
							if(String.valueOf(dpt.getDepartmentid()).equals(property)){
								continue;
							}
							buffer.append("<option value=\"")
								.append(dpt.getDepartmentid())
								.append("\"");
							if(null != parentid){
								if(dpt.getDepartmentid().compareTo(parentid) == 0){
									buffer.append("selected=\"selected\"");
								}
							}
							buffer.append(">")
								.append(getDepartmentCascadeTitle(dpt.getDepartmentid()))
							.append("</option>");
						}
					}
					message = buffer.toString();
				}
			}else if("seg".equalsIgnoreCase(type)){
				if("name".equalsIgnoreCase(action)){ //通过栏目ID查找栏目中文名称
					Segment segment = getSegment(Long.valueOf(property));
					if(segment == null){
						message = "顶级分类";
					}else{
						message = segment.getTitle();
					}
				}
				if("select".equalsIgnoreCase(action)){ //显示所有的栏目
					StringBuffer buffer = new StringBuffer();
					Iterator<CascadeCollection<Segment>> its = getAllSegments();
					
					Segment current = null;
					Long parentid = null;
					if(null != property && !"".equals(property.trim())){
						current = getSegment(Long.valueOf(property));
						parentid = current.getParentid();
					}
					
					buffer.append("<option value=\"" + ConstantDB.CASCADE_ID_TOP+"\">顶级分类</option>");
					if(its != null){
						while(its.hasNext()){
							Segment seg = its.next().getCurrent();
							if(String.valueOf(seg.getSegmentid()).equals(property)){
								continue;
							}
							buffer.append("<option value=\"")
								.append(seg.getSegmentid())
								.append("\"");
							if(null != parentid){
								if(seg.getSegmentid().compareTo(parentid) == 0){
									buffer.append("selected=\"selected\"");
								}
							}
							buffer.append(">")
								.append(getSegmentCascadeTitle(seg.getSegmentid()))
							.append("</option>");
						}
					}
					message = buffer.toString();
				}
			}
			writer.print(message);
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		return (SKIP_BODY);
	}
	/**
	 * 获得当前Department的级联格式title显示 例如 国家-省-市-县
	 * @return
	 */
	public String getDepartmentCascadeTitle(Long id){
		String title = "";
		Department current = getDepartment(id);
		if(ConstantDB.CASCADE_ID_TOP.compareTo(current.getParentid()) == 0){
			title = current.getTitle();
		}else{
			title = getDepartmentCascadeTitle(current.getParentid()) + "-" + current.getTitle();
		}
		return title;
	}
	/**
	 * 获得当前Segment的级联格式title显示 例如 国家-省-市-县
	 * @return
	 */
	public String getSegmentCascadeTitle(Long id){
		String title = "";
		Segment current = getSegment(id);
		if(ConstantDB.CASCADE_ID_TOP.compareTo(current.getParentid()) == 0){
			title = current.getTitle();
		}else{
			title = getSegmentCascadeTitle(current.getParentid()) + "-" + current.getTitle();
		}
		return title;
	}
	public Department getDepartment(Long departmentid){
		try{
			if(ConstantDB.CASCADE_ID_TOP.compareTo(departmentid) == 0)
				return null;
			CascadeCollection<Department> cs = (CascadeCollection<Department>) CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).get(Constants.CACHE_KEY_DEPARTMENT_CASCADECOLLECTION);
			if(cs != null)
				return cs.getAllDatas().get(departmentid).getCurrent();
		}catch(Exception e){
			logger.debug(e);
		}
		return null;
	}
	public Segment getSegment(Long segmentid){
		try{
			if(ConstantDB.CASCADE_ID_TOP.compareTo(segmentid) == 0)
				return null;
			CascadeCollection<Segment> cs = (CascadeCollection<Segment>) CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).get(Constants.CACHE_KEY_SEGMENT_CASCADECOLLECTION);
			if(cs != null)
				return cs.getAllDatas().get(segmentid).getCurrent();
		}catch(Exception e){
			logger.debug(e);
		}
		return null;
	}
	public Iterator<CascadeCollection<Department>> getAllDepartments(){
		try{
			CascadeCollection<Department> cs = (CascadeCollection<Department>) CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).get(Constants.CACHE_KEY_DEPARTMENT_CASCADECOLLECTION);
			if(cs != null)
				return cs.getAllDatas().values().iterator();
		}catch(Exception e){
			logger.debug(e);
		}
		return null;
	}
	public Iterator<CascadeCollection<Segment>> getAllSegments(){
		try{
			CascadeCollection<Segment> cs = (CascadeCollection<Segment>) CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).get(Constants.CACHE_KEY_SEGMENT_CASCADECOLLECTION);
			if(cs != null)
				return cs.getAllDatas().values().iterator();
		}catch(Exception e){
			logger.debug(e);
		}
		return null;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}
}
